<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2017/12/10
 * Time: 22:26
 */

namespace controller;


use controller\base\Base;
use logic\EggLogic;
use model\Egg;
use model\LogEgg;
use model\Releases;

class Cj extends Base
{
    /**
     * @param int $id id
     * @param int $rid rid
     */
    public function index($id, $rid)
    {
        $this->header();
        $releases = new Releases();
        $data     = $releases->row([
            'id'        => $rid,
            'action_id' => $id
        ]);


        $this->assign('num', EggLogic::getNum($id));
        $this->assign('data', $data);
        $this->fetch();
    }

    /**
     * @param int $id id
     * @param int $rid rid
     * @return string
     */
    public function post($id, $rid)
    {
        $this->checkActionTime();
        $num = EggLogic::getNum($id);
        if ($num <= 0) {
            return json(['code' => 'hasno']);
        }

        if (!$this->is_vote) {
            return ['state' => false, 'msg' => '投票时间未开始'];
        }
        if ($this->is_vote_end) {
            return ['state' => false, 'msg' => '投票时间已结束'];
        }

        $logEgg = new LogEgg();
//        限制每天砸蛋数量
//        $logEgg->where('created', now('Y-m-d'), '>=');
//        $logEggNum = $logEgg->count('id', []);
//        log_file()->set($logEgg->last_sql);
//        if ($this->actionListData['tamp_egg_num'] <= $logEggNum) {
//            return ['state' => false, 'msg' => '今日砸蛋数量已满'];
//        }

        $egg = new Egg();
        $egg->updateNum(-1, session('openid'), $id);
        $poll     = rand(3, 10);
        $releases = new Releases();
        $releases->addEggPoll($id, $rid, $poll);

        $logEgg->insert(
            [
                'action_id'   => $id,
                'open_id'     => session('openid'),
                'releases_id' => $rid,
                'num'         => $poll,
                'created'     => now()
            ]
        );

        return json(['code' => 'ok', 'left' => $num - 1, 'msg' => $poll]);
    }
}